/*
 * EEN_PhuongView.java
 */
package crfsvm.crf.een_phuong;

import java.awt.Color;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import java.io.*; //my addition

/**
 * The application's main frame.
 */
public class EEN_PhuongView extends FrameView {

    public EEN_PhuongView(SingleFrameApplication app) {
        super(app);

        initComponents();
        jButton3.setText("Predict");
        jButton1.setText("Predict with Confidence");

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = EEN_PhuongApp.getApplication().getMainFrame();
            aboutBox = new EEN_PhuongAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        EEN_PhuongApp.getApplication().show(aboutBox);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    JTextArea textComp = new JTextArea();

    public void highlight(JTextComponent textComp, String pattern, int i, Highlighter hilite, String color) throws BadLocationException {
//        removeHighlights(textComp);
        try {
            Document doc = textComp.getDocument();
            String text = doc.getText(0, doc.getLength());
//            text = text.substring(i, text.length());
            int pos = i;
            while ((pos = text.indexOf(pattern, pos)) >= 0) {
                if (color.equalsIgnoreCase("num")) {
                    hilite.addHighlight(pos, pos + pattern.length(), numHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("time")) {
                    hilite.addHighlight(pos, pos + pattern.length(), timeHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("per")) {
                    hilite.addHighlight(pos, pos + pattern.length(), perHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("misc")) {
                    hilite.addHighlight(pos, pos + pattern.length(), miscHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("pct")) {
                    hilite.addHighlight(pos, pos + pattern.length(), pctHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("cur")) {
                    hilite.addHighlight(pos, pos + pattern.length(), curHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("loc")) {
                    hilite.addHighlight(pos, pos + pattern.length(), locHighlightPainter);
                    pos += pattern.length();
                } else if (color.equalsIgnoreCase("org")) {
                    hilite.addHighlight(pos, pos + pattern.length(), orgHighlightPainter);
                    pos += pattern.length();
                }
            }
        } catch (BadLocationException e) {
        }
    }
    Highlighter.HighlightPainter numHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.GREEN);
    Highlighter.HighlightPainter timeHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.RED);
    Highlighter.HighlightPainter perHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.CYAN);
    Highlighter.HighlightPainter miscHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.YELLOW);
    Highlighter.HighlightPainter pctHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.GRAY);
    Highlighter.HighlightPainter curHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.blue);
    Highlighter.HighlightPainter locHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.LIGHT_GRAY);
    Highlighter.HighlightPainter orgHighlightPainter = (HighlightPainter) new MyHighlightPainter(Color.MAGENTA);

    class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

        public MyHighlightPainter(Color color) {
            super(color);
        }
    }

    class NamedEntity {

        public String type; //time, per,org, loc
        public String instance;
        public int beginIdx;
        public int endIdx;
    }

    class nameEntityForConfidence
    {
        public String type; //time, per,org, loc
        public String instance;
        public int beginIdx;
        public int endIdx;
        public String confidence;
    }

    private NamedEntity getNextEntity(String data, int curpos) {
        NamedEntity nent = null;

        int beginOpenTag = data.indexOf("<", curpos);
        int endOpenTag = data.indexOf(">", beginOpenTag);

        if (beginOpenTag == -1 || endOpenTag == -1) {
            return null;
        }

        String openTag = data.substring(beginOpenTag + 1, endOpenTag).toLowerCase();
        String closeTag = "</" + openTag + ">";

        int closeTagIdx = data.indexOf(closeTag, endOpenTag + 1);

        if (closeTagIdx == -1) {
            return null;
        }

        nent = new NamedEntity();

        nent.beginIdx = beginOpenTag;
        nent.endIdx = closeTagIdx + closeTag.length();
        nent.instance = data.substring(endOpenTag + 1, closeTagIdx).trim();
        nent.type = openTag;

        return nent;
    }

    private nameEntityForConfidence getNextEntityConfidence(String data, int curpos) {
        nameEntityForConfidence nent = null;

        int beginOpenTag = data.indexOf("<", curpos);
        int endOpenTag = data.indexOf(">", beginOpenTag);

        if (beginOpenTag == -1 || endOpenTag == -1) {
            return null;
        }

        String temp = data.substring(beginOpenTag + 1, endOpenTag).toLowerCase();
        int index = temp.indexOf(" ");
        String openTag = temp.substring(0, index);
        String confi = temp.substring(index + 1);
        String closeTag = "</" + openTag + ">";

        int closeTagIdx = data.indexOf(closeTag, endOpenTag + 1);

        if (closeTagIdx == -1) {
            return null;
        }

        nent = new nameEntityForConfidence();

        nent.beginIdx = beginOpenTag;
        nent.endIdx = closeTagIdx + closeTag.length();
        nent.instance = data.substring(endOpenTag + 1, closeTagIdx).trim();
        nent.type = openTag;
        nent.confidence = confi;

        return nent;
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane1.setViewportView(jTextArea1);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(EEN_PhuongView.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 409, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40)
                        .addComponent(jButton2))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(231, 231, 231)
                        .addComponent(jButton3)
                        .addGap(60, 60, 60)
                        .addComponent(jButton1))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1014, Short.MAX_VALUE)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(EEN_PhuongView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 1038, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 870, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            // TODO add your handling code here:
            jTextArea1.setText("");
            CopyFile copyFile = new CopyFile();
            String tagg = "." + File.separator + "vnTagger" + File.separator + "input.txt";
            copyFile.copyfile(jTextField1.getText(), tagg);
            vnTokenizer vntokenizer = new vnTokenizer();
            try {
                //vntokenizer.token();
                tokenizeVietnamese.token();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }
            JVnRecognizer jVnRecognizer = new JVnRecognizer();
            String[] args = new String[4];
            args[0] = "-modeldir";
            args[1] = "./model";
            args[2] = "-inputfile";
            args[3] = "input.txt";
            jVnRecognizer.main(args);
            BufferedReader in = null;
            String line = null;
            try {
                try {
                    in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt.wseg"), "UTF-8"));
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }
            String ret = "", myret = "";
            Highlighter hilite = jTextArea1.getHighlighter();
            
            //My code
            File f = new File(jTextField1.getText());
            String myPath = "." + File.separator + "data" + File.separator + "mypredicted" + File.separator + f.getName() + ".predictedConfi";
            BufferedWriter predict = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(myPath), "UTF-8"));
            //End my code

            try {
                while ((line = in.readLine()) != null) {
                    if (line.trim().length() == 0) {
                        ret += "\n\n";
                        myret += "\n\n";
                        continue;
                    }
                    //NamedEntity nent;
                    nameEntityForConfidence nent;
                    int curpos = 0;
                    while ((nent = getNextEntityConfidence(line, curpos)) != null) { //nent = getNextEntity(line, curpos)
                        String aheadStr = line.substring(curpos, nent.beginIdx);
                        VnStringTokenizer tk = new VnStringTokenizer(aheadStr, " {}");
                        while (tk.hasMoreTokens()) {
                            String token = tk.nextToken();
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                        }
                        // myret += "<" + nent.type + ">" + " ";
                        //my code
                        myret += "<" + nent.type + " " + nent.confidence + ">" + " ";
                        ret += "<" + nent.type + " " + nent.confidence + ">" + " ";
                        jTextArea1.append("<" + nent.type + " " + nent.confidence + ">" + " ");
                        //end my code
                        VnStringTokenizer entTk = new VnStringTokenizer(nent.instance, " {}");
                        while (entTk.hasMoreTokens()) {
                            String token = entTk.nextToken();
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            String retOld = ret;
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                            try {
                                highlight(jTextArea1, token.trim(), retOld.length(), hilite, nent.type);
                            } catch (BadLocationException ex) {
                                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        //my code
                        myret += "</" + nent.type + ">" + " ";
                        ret += "</" + nent.type + ">" + " ";
                        jTextArea1.append("</" + nent.type + ">" + " ");
                        //end my code

                        curpos = nent.endIdx + 1;
                    }
                    if (curpos < line.length()) {
                        String remain = line.substring(curpos, line.length());
                        VnStringTokenizer tk = new VnStringTokenizer(remain, " ");
                        while (tk.hasMoreTokens()) {
                            String token = tk.nextToken();
                            //System.out.println("token = " + token);
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                        }
                    }
                    jTextArea1.append("\n\n");
                }
                predict.write(myret);
                predict.close();
            } catch (IOException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    //my code
    private  boolean checkPunctuation(String line)
    {
        boolean result = false;
         String[] punctuations = {".", "," , "!", "(", ")", "[", "]", "{", "}", "$", "?", "@", "\"", "-", "/", "...", ":", "'", ";", "*", "+" , "#",
        "%", "^", "&", "=", "|", "~", "`"};
         
         for (int i = 0; i < punctuations.length; i++)
             if (punctuations[i].equals(line))
             {
                 result = true;
                 break;
             }
         
         return result;
    }
   // end my code

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        JFileChooser choose = new JFileChooser();
        int f = choose.showOpenDialog(mainPanel);
        if (f == JFileChooser.APPROVE_OPTION) {
            File inFile = choose.getSelectedFile();
            jTextField1.setText(inFile.getPath());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
         try {
            // TODO add your handling code here:
            jTextArea1.setText("");
            
            CopyFile copyFile = new CopyFile();
            String tagg = "." + File.separator + "vnTagger" + File.separator + "input.txt";
            copyFile.copyfile(jTextField1.getText(), tagg);
            vnTokenizer vntokenizer = new vnTokenizer();
            try {
                vntokenizer.token();
                tokenizeVietnamese.token();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }

            JVnRecognizer jVnRecognizer = new JVnRecognizer();
            String[] args = new String[4];
            args[0] = "-modeldir";
            args[1] = "./model";
            args[2] = "-inputfile";
            args[3] = "input.txt";
            jVnRecognizer.main(args);
            BufferedReader in = null;
            String line = null;
            try {
                try {
                    in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt.wseg"), "UTF-8"));
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }
            String ret = "", myret = "";
            Highlighter hilite = jTextArea1.getHighlighter();

            //My code
            File f = new File(jTextField1.getText());
            String myPath = "." + File.separator + "data" + File.separator + "mypredicted" + File.separator + f.getName() + ".predicted";
            BufferedWriter predict = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(myPath), "UTF-8"));
            //End my code

            try {
                while ((line = in.readLine()) != null) {
                    if (line.trim().length() == 0) {
                        ret += "\n\n";
                        myret += "\n\n";
                        continue;
                    }
                    //NamedEntity nent;
                    nameEntityForConfidence nent;
                    int curpos = 0;
                    while ((nent = getNextEntityConfidence(line, curpos)) != null) { //nent = getNextEntity(line, curpos)
                        String aheadStr = line.substring(curpos, nent.beginIdx);
                        VnStringTokenizer tk = new VnStringTokenizer(aheadStr, " {}");
                        while (tk.hasMoreTokens()) {
                            String token = tk.nextToken();
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                        }
                        // myret += "<" + nent.type + ">" + " ";
                        //my code
                        myret += "<" + nent.type + ">" + " ";
                        //ret += "<" + nent.type + " " + nent.confidence + ">" + " ";
                        //jTextArea1.append("<" + nent.type + " " + nent.confidence + ">" + " ");
                        //end my code
                        VnStringTokenizer entTk = new VnStringTokenizer(nent.instance, " {}");
                        while (entTk.hasMoreTokens()) {
                            String token = entTk.nextToken();
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            String retOld = ret;
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                            try {
                                highlight(jTextArea1, token.trim(), retOld.length(), hilite, nent.type);
                            } catch (BadLocationException ex) {
                                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        //my code
                        myret += "</" + nent.type + ">" + " ";
                        //ret += "</" + nent.type + ">" + " ";
                        //jTextArea1.append("</" + nent.type + ">" + " ");
                        //end my code

                        curpos = nent.endIdx + 1;
                    }
                    if (curpos < line.length()) {
                        String remain = line.substring(curpos, line.length());
                        VnStringTokenizer tk = new VnStringTokenizer(remain, " ");
                        while (tk.hasMoreTokens()) {
                            String token = tk.nextToken();
                            //System.out.println("token = " + token);
                            // my code
                            if (checkPunctuation(token))
                                myret += token + " ";
                            else
                                myret += "[" + token + "] ";
                            //end my code
                            token += " ";
                            ret += token;
                            //myret += token;
                            jTextArea1.append(token);
                        }
                    }
                    jTextArea1.append("\n\n");
                }
                predict.write(myret);
                predict.close();
            } catch (IOException ex) {
                Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EEN_PhuongView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
